package com.ornate.core.tree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class TreeBuilder {

	private TreeNode getNodeById(List<TreeNode> records, String id) {
		TreeNode result = null;
		for (Iterator<TreeNode> iterator = records.iterator(); iterator.hasNext();) {
			TreeNode node = iterator.next();
			if (StringUtils.equals(node.getId(), id)) {
				result = node;
				break;
			}
		}
		return result;
	}

	private List<TreeNode> getNodesByParentId(List<TreeNode> records, String parentId) {
		List<TreeNode> result = new ArrayList<TreeNode>();
		for (Iterator<TreeNode> iterator = records.iterator(); iterator.hasNext();) {
			TreeNode node = iterator.next();
			if (StringUtils.equals(node.getParentId(), parentId)) {
				result.add(node);
			}
		}
		return result;
	}

	private List<TreeNode> convert(List<Map<String, Object>> records, ITreeNodeConverter converter) {
		List<TreeNode> result = new ArrayList<TreeNode>();
		for (Iterator<Map<String, Object>> iterator = records.iterator(); iterator.hasNext();) {
			result.add(converter.convert(iterator.next()));
		}
		return result;
	}

	public List<TreeNode> build(List<Map<String, Object>> records, String rootParentId, ITreeNodeConverter converter) {
		return build(convert(records, converter), rootParentId);
	}

	public List<TreeNode> build(List<TreeNode> records, String rootParentId) {
		List<TreeNode> root = getNodesByParentId(records, rootParentId);
		for (Iterator<TreeNode> iterator = records.iterator(); iterator.hasNext();) {
			TreeNode child = iterator.next();
			TreeNode node = getNodeById(records, child.getParentId());
			if (node != null) node.getChildren().add(child);
		}
		return root;
	}

}
